package com.renwei.yunlong.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.me.CompanyInfoActivity;
import com.renwei.yunlong.activity.me.DisplayEnterpriseInfoActivity;
import com.renwei.yunlong.activity.me.DisplayUserInfoActivity;
import com.renwei.yunlong.activity.me.ObjectInformationtActivity;
import com.renwei.yunlong.activity.work.WorkDetailSlaActivity;
import com.renwei.yunlong.activity.work.WorkInformationActivity;
import com.renwei.yunlong.adapter.WorkDetailObjectAdapter;
import com.renwei.yunlong.base.BaseLazyFragment;
import com.renwei.yunlong.bean.MuchAssetBean;
import com.renwei.yunlong.bean.WorkInformationBean;
import com.renwei.yunlong.event.WorkPageRefreshEvent;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.view.RatingBar;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 工单  详情  页面
 * <p>
 * Created by Administrator on 2017/9/6.
 */

public class WorkDetailsFragment extends BaseLazyFragment implements View.OnClickListener, HttpTaskListener, BaseRecyclerViewAdapter.OnItemClickLitener {

    @Bind(R.id.tv_number)
    TextView tvNumber;
    @Bind(R.id.tv_state)
    TextView tvState;
    @Bind(R.id.tv_level)
    TextView tvLevel;
    @Bind(R.id.tv_send_company)
    TextView tvSendCompany;
    @Bind(R.id.rl_iv_send_company)
    RelativeLayout ivSendCompany;
    @Bind(R.id.tv_send_person)
    TextView tvSendPerson;
    @Bind(R.id.rl_iv_send_person)
    RelativeLayout ivSendPerson;
    @Bind(R.id.tv_send_time)
    TextView tvSendTime;
    @Bind(R.id.tv_complete_time)
    TextView tvCompleteTime;
    @Bind(R.id.tv_description)
    TextView tvDescription;
    @Bind(R.id.tv_detailed)
    TextView tvDetailed;
    @Bind(R.id.tv_project)
    TextView tvProject;
    @Bind(R.id.ll_project)
    RelativeLayout llProject;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.tv_expand)
    TextView tvExpand;
    @Bind(R.id.rl_expand)
    RelativeLayout rlExpand;
    @Bind(R.id.rl_iv_work)
    RelativeLayout ivWork;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.tv_deal_company)
    TextView tvDealCompany;
    @Bind(R.id.rl_iv_deal_company)
    RelativeLayout ivDealCompany;
    @Bind(R.id.tv_deal_person)
    TextView tvDealPerson;
    @Bind(R.id.rl_iv_deal_person)
    RelativeLayout ivDealPerson;
    @Bind(R.id.rl_grade)
    RelativeLayout rlGrade;
    @Bind(R.id.rtb_star_fives)
    RatingBar rtbStarFives;
    @Bind(R.id.ll_evaluate)
    LinearLayout llEvaluate;
    @Bind(R.id.ll_complete)
    LinearLayout llComplete;
    @Bind(R.id.ll_sla)
    LinearLayout llSla;
    @Bind(R.id.tv_evaluate)
    TextView tvEvaluate;
    @Bind(R.id.tv_isOut)
    TextView tvIsOut;
    @Bind(R.id.tv_leader)
    TextView tvLeader;
    @Bind(R.id.tv_sla)
    TextView tvSla;
    @Bind(R.id.tv_sla1)
    TextView tvSla1;
    @Bind(R.id.tv_sla2)
    TextView tvSla2;
    @Bind(R.id.tv_sla3)
    TextView tvSla3;
    @Bind(R.id.rl_iv_sla)
    RelativeLayout ivSla;
    private String requestId;
    private String outsourceFlag;
    private WorkInformationBean workInformationBean;
    private WorkDetailObjectAdapter adapter;
    private List<MuchAssetBean> objectList;
    private boolean isWork;

    @SuppressLint("ValidFragment")
    public WorkDetailsFragment(String requestId, String outsourceFlag, boolean isWork) {
        this.requestId = requestId;
        this.outsourceFlag = outsourceFlag;
        this.isWork = isWork;
    }

    public WorkDetailsFragment() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_work_details;
    }

    @Override
    public void onLazyLoad() {
        initView();
        initData();
    }

    public void initView() {
        EventBus.getDefault().register(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setNestedScrollingEnabled(false);
        adapter = new WorkDetailObjectAdapter(getContext(), isWork);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickLitener(this);

        if ("1".equals(companyType) && ("0".equals(outsourceFlag) || TextUtils.isEmpty(outsourceFlag))) {
            adapter.setShow(false);
            llProject.setVisibility(View.GONE);
        } else {
            adapter.setShow(true);
            llProject.setVisibility(View.VISIBLE);
        }

        if (isWork) {
            ivWork.setVisibility(View.GONE);
            tvState.setVisibility(View.VISIBLE);
        } else {
            ivWork.setVisibility(View.VISIBLE);
            tvState.setVisibility(View.GONE);
        }

        ivWork.setOnClickListener(this);
        ivSendCompany.setOnClickListener(this);
        ivSla.setOnClickListener(this);
        ivSendPerson.setOnClickListener(this);
        ivDealCompany.setOnClickListener(this);
        ivDealPerson.setOnClickListener(this);
        rlExpand.setOnClickListener(this);
    }

    public void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("requestId", requestId);
        ServiceRequestManager.getManager().getWorkDetail(getContext(), StringUtils.value(outsourceFlag), true, JsonMapUtil.mapToJson(map), this);
    }

    private void setData() {
        WorkInformationBean.RowsBean bean = workInformationBean.getRows();
        // 工单ID
        tvNumber.setText(bean.getWorkOrder());
        // 工单状态
        if ("1".equals(bean.getOutsourceFlag())) {
            tvIsOut.setBackgroundResource(R.drawable.shape_card_ff7d8c);
            tvIsOut.setText("外");
        } else {
            tvIsOut.setBackgroundResource(R.drawable.shape_card_76c56d);
            tvIsOut.setText("内");
        }
        if ("3".equals(bean.getIsLeader())) {
            tvLeader.setVisibility(View.VISIBLE);
            tvLeader.setBackgroundResource(R.drawable.shape_card_5cc9ff);
            tvLeader.setText("副");
        } else if ("2".equals(bean.getIsLeader())) {
            tvLeader.setVisibility(View.VISIBLE);
            tvLeader.setBackgroundResource(R.drawable.shape_card_e9981f);
            tvLeader.setText("主");
        } else {
            tvLeader.setVisibility(View.GONE);
        }
        if ("0".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_e64545);
            tvState.setText("未指派");
        } else if ("3".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_76c56d);
            tvState.setText("已指派");
        } else if ("4".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_e9981f);
            tvState.setText("处理中");
        } else if ("5".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_999691);
            tvState.setText("已关闭");
        } else if ("7".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_e64545);
            tvState.setText("挂起");
        } else if ("9".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_e64545);
            tvState.setText("待确认");
        } else if ("10".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_76c56d);
            tvState.setText("已解决");
            //显示 满意度和评价内容
            llComplete.setVisibility(View.VISIBLE);
            try {
                rtbStarFives.setStar(Float.valueOf(bean.getServerGrade()));
                tvEvaluate.setText(bean.getEvaluateView());
            } catch (NumberFormatException e) {
                rtbStarFives.setStar(0);
            }
        } else if ("11".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_999691);
            tvState.setText("已取消");
        } else if ("16".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_e64545);
            tvState.setText("出发中");
        } else if ("17".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_76c56d);
            tvState.setText("已到达");
        } else if ("18".equals(bean.getNowStat())) {
            tvState.setBackgroundResource(R.drawable.shape_card_e64545);
            tvState.setText("未指派");
        }
        // 故障等级
        tvLevel.setText(bean.getLevelName());
        // 发起时间
        tvSendTime.setText(bean.getSendDate().replace("T", " "));
        // 完成时间
//        if ("0".equals(bean.getIsOverdue())) {
        tvCompleteTime.setTextColor(Color.parseColor("#333333"));
        tvCompleteTime.setText(bean.getCompleteDate().replace("T", " "));
//        } else {
//            tvCompleteTime.setTextColor(Color.parseColor("#E64545"));
//            tvCompleteTime.setText("逾期");
//        }
        // 简要说明
        tvDescription.setText(bean.getTitle());
        // 详细说明
        tvDetailed.setText(bean.getRequestContent());
        // 所属项目
        tvProject.setText(bean.getContractName());
        // 处理多对象
        String hardWareIds = bean.getHardWareIds();
        objectList = new Gson().fromJson(hardWareIds, new TypeToken<List<MuchAssetBean>>() {
        }.getType());
        // 展开 收起
        if (objectList == null || objectList.size() == 0) {
            objectList = new ArrayList<>();
            objectList.add(new MuchAssetBean());
            adapter.setData(objectList);
            rlExpand.setVisibility(View.GONE);
        } else if (objectList.size() == 1) {
            adapter.setData(objectList);
            rlExpand.setVisibility(View.GONE);
        } else if (objectList.size() > 1) {
            List<MuchAssetBean> list = new ArrayList<>();
            list.add(objectList.get(0));
            adapter.setData(list);
            rlExpand.setVisibility(View.VISIBLE);
            tvExpand.setText("展开对象(" + objectList.size() + ")");
        }
        // SLA
        if ("10".equals(bean.getNowStat())
                && (!TextUtils.isEmpty(bean.getIsSlaResponse())
                || !TextUtils.isEmpty(bean.getIsSlaArrive())
                || !TextUtils.isEmpty(bean.getIsSlaDealt()))) {
            ivSla.setVisibility(View.VISIBLE);
            llSla.setVisibility(View.VISIBLE);
            tvSla.setVisibility(View.GONE);
            if ("1".equals(bean.getIsSlaResponse())) {
                tvSla1.setText("响应达标");
                tvSla1.setBackgroundResource(R.drawable.shape_card_76c56d);
            } else if ("0".equals(bean.getIsSlaResponse())) {
                tvSla1.setText("响应未达标");
                tvSla1.setBackgroundResource(R.drawable.shape_card_e64545);
            } else {
                tvSla1.setVisibility(View.GONE);
            }

            if ("1".equals(bean.getIsSlaArrive())) {
                tvSla2.setText("到场达标");
                tvSla2.setBackgroundResource(R.drawable.shape_card_76c56d);
            } else if ("0".equals(bean.getIsSlaArrive())) {
                tvSla2.setText("到场未达标");
                tvSla2.setBackgroundResource(R.drawable.shape_card_e64545);
            } else {
                tvSla2.setVisibility(View.GONE);
            }

            if ("1".equals(bean.getIsSlaDealt())) {
                tvSla3.setText("处理达标");
                tvSla3.setBackgroundResource(R.drawable.shape_card_76c56d);
            } else if ("0".equals(bean.getIsSlaDealt())) {
                tvSla3.setText("处理未达标");
                tvSla3.setBackgroundResource(R.drawable.shape_card_e64545);
            } else {
                tvSla3.setVisibility(View.GONE);
            }
        } else {
            ivSla.setVisibility(View.GONE);
            llSla.setVisibility(View.GONE);
            tvSla.setVisibility(View.VISIBLE);
            tvSla.setText((TextUtils.isEmpty(bean.getDays()) ? "0" : bean.getDays()) + "天" +
                    (TextUtils.isEmpty(bean.getHours()) ? "0" : bean.getHours()) + "小时");
        }
        //工单类型
        if ("0".equals(bean.getOutsourceFlag())) {
            tvType.setText("内部工单");
        } else if ("1".equals(bean.getOutsourceFlag())) {
            tvType.setText("外部工单");
        }
        // 业主企业  处理企业
        if ("1".equals(companyType) && "0".equals(bean.getOutsourceFlag())) {
            tvSendCompany.setText(bean.getOwnerName());
            tvDealCompany.setText(bean.getServerName());
        } else {
            tvSendCompany.setText(bean.getServerName());
            tvDealCompany.setText(bean.getServiceProviderName());
        }
        // 发起人
        if (TextUtils.isEmpty(bean.getMobilePhone())) {
            tvSendPerson.setText(bean.getSendUserName());
        } else {
            tvSendPerson.setText(bean.getSendUserName() +
                    "，" + bean.getMobilePhone());
        }
        // 处理人
        if (TextUtils.isEmpty(bean.getResponseUserPhone())) {
            tvDealPerson.setText(bean.getResponseUserName());
        } else {
            tvDealPerson.setText(bean.getResponseUserName() +
                    "，" + bean.getResponseUserPhone());
        }
        if (!TextUtils.isEmpty(tvSendCompany.getText().toString()) && isWork) {
            ivSendCompany.setVisibility(View.VISIBLE);
        } else {
            ivSendCompany.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(tvSendPerson.getText().toString())) {
            if ("2".equals(companyType) && ("0".equals(outsourceFlag) || TextUtils.isEmpty(outsourceFlag))) {
                ivSendPerson.setVisibility(View.GONE);
            } else {
                if (isWork) {
                    ivSendPerson.setVisibility(View.VISIBLE);
                } else {
                    ivSendPerson.setVisibility(View.GONE);
                }
            }
        } else {
            ivSendPerson.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(tvDealCompany.getText().toString()) && isWork) {
            ivDealCompany.setVisibility(View.VISIBLE);
        } else {
            ivDealCompany.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(tvDealPerson.getText().toString()) && isWork) {
            ivDealPerson.setVisibility(View.VISIBLE);
        } else {
            ivDealPerson.setVisibility(View.GONE);
        }
    }


    /**
     * 当前刷新
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(WorkPageRefreshEvent event) {
        initData();
    }


    @Override
    public void onItemClick(View view, int position) {
        ObjectInformationtActivity.OpenAcitivity(getContext(), "对象详情",
                workInformationBean.getRows().getOutsourceFlag(), adapter.getItem(position).getAssetId(), adapter.getItem(position).getAssetName());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_iv_send_company: // 业主单位
                if ("1".equals(companyType)) {
                    DisplayEnterpriseInfoActivity.OpenActivity(getContext(), workInformationBean.getRows().getOwnerCode());
                } else {
                    if ("0".equals(workInformationBean.getRows().getOutsourceFlag())) {
                        CompanyInfoActivity.OpenActivity(getContext(), null, workInformationBean.getRows().getOwnerCode());
                    } else {
                        DisplayEnterpriseInfoActivity.OpenActivity(getContext(), workInformationBean.getRows().getOwnerCode());
                    }
                }
                break;
            case R.id.rl_iv_send_person:  // 发起人
                DisplayUserInfoActivity.OpenActivity(getContext(), workInformationBean.getRows().getSendUser()
                        , "1".equals(companyType) ? "" : outsourceFlag);
                break;
            case R.id.rl_iv_deal_company:  // 处理企业
                if ("1".equals(companyType)) {
                    if ("0".equals(workInformationBean.getRows().getOutsourceFlag())) {
                        if ("1".equals(workInformationBean.getRows().getIsSelfFlag())) {
                            CompanyInfoActivity.OpenActivity(getContext(), null, workInformationBean.getRows().getServiceProviderCode());
                        } else {
                            DisplayEnterpriseInfoActivity.OpenActivity(getContext(), workInformationBean.getRows().getOwnerCode());
                        }
                    } else {
                        DisplayEnterpriseInfoActivity.OpenActivity(getContext(), workInformationBean.getRows().getServiceProviderCode());
                    }
                } else {
                    DisplayEnterpriseInfoActivity.OpenActivity(getContext(), workInformationBean.getRows().getServiceProviderCode());
                }
                break;
            case R.id.rl_iv_deal_person:  // 处理人
                DisplayUserInfoActivity.OpenActivity(getContext(), workInformationBean.getRows().getResponseUserId()
                        , "2".equals(companyType) ? "" : outsourceFlag);
                break;
            case R.id.rl_iv_work:  // 工单
                WorkInformationActivity.OpenActivity(getContext(), requestId, requestId, outsourceFlag);
                break;
            case R.id.rl_iv_sla: //sla
                WorkDetailSlaActivity.OpenActivity(getContext(), requestId, outsourceFlag);
                break;
            case R.id.rl_expand:
                if (adapter.getItemCount() == 1) {
                    adapter.setData(objectList);
                    tvExpand.setText("收起对象");
                } else {
                    List<MuchAssetBean> list = new ArrayList<>();
                    list.add(objectList.get(0));
                    adapter.setData(list);
                    tvExpand.setText("展开对象(" + objectList.size() + ")");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                workInformationBean = new Gson().fromJson(result, WorkInformationBean.class);
                if (workInformationBean.getMessage().getCode() == 200) {
                    setData();
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getContext().getResources().getString(R.string.net_work_error));
    }

}
